#include <allegro.h>
#include "gui.h"
#include "main.h"
#include "colors.h"
#include "resources/resources.h"

static void inventory_draw (Hud* h)
{
	Actor* p = h->active_player;
	int x = 8; // top left corner of inventory squares 5-group
	int y = DISPLAY_HEIGHT-26;
	
	masked_blit(bmp.hud, buffer, 0, 56, x-3, y-3, 98, 22);
	
	for (int i = 0; i < 5; i++) {
		Item* item = &items[p->character->inventory.slot[i]];
		if (item->type == ITEM_NOTHING) {
			masked_blit(bmp.hud, buffer, i*16, 80, i*19+x, y, 16, 16);
		} else {
			masked_blit(bmp.icons, buffer, item->icon_x*16, item->icon_y*16, 
			            i*19+x, y, 16, 16);
		}
	}
}

static void hp_draw (Hud* hud)
{
	int x = 8;
	int y = 8;
	int pxhp = 100 * hud->hp_display / hud->active_player->hp_max;
	int w_filled = MAX (0, pxhp);
	masked_blit(bmp.hud, buffer, 0, 0, x-3, y-3, 106, 21);
	masked_blit(bmp.hud, buffer, 115, 3, x, y, w_filled, 12);
}

#if TOWERHACK_DEBUG
#include "map_display.h"
#include "game.h"
#endif

static void treasure_draw (Hud* hud)
{
	int x = DISPLAY_WIDTH-8;
	int y = 8;
	textprintf_right_ex (buffer, font, x, y, makecol(255,255,0), -1, "%d", hud->active_player->character->gold);
	
	#if TOWERHACK_DEBUG
	Coord c = hud->active_player->coord;
	textprintf_right_ex (buffer, font, x, y+12, makecol(255,0,0), -1, "char at %d/%d/%d", c.x, c.y, c.z);
	
	int tile_x, tile_y, subtile;
	mouse_get_coords (NULL, NULL, NULL, NULL, &tile_x, &tile_y, &subtile);
	textprintf_right_ex (buffer, font, x, y+24, makecol(255,0,0), -1,
	                     "mouse tile[st] %d/%d [%d]", tile_x, tile_y, subtile);
	
	if ((tile_x >= 0) && (tile_y >= 0) && (tile_x < MAP_WIDTH) && (tile_y < MAP_HEIGHT)) {
		Tile* tile = &TILE(&the_game.map, tile_x, tile_y, hud->active_player->coord.z);
		textprintf_right_ex (buffer, font, x, y+36, makecol(255,0,0), -1, "fg: %d", tile->gfx_wallfg[subtile]);
	}
	#endif
}

Hud* hud_create(Actor* p)
{
	Hud* h = malloc(sizeof(Hud));
	h->active_player = p;
	h->hp_display = p->hp_max;
	return h;
}

void hud_update(Hud* h)
{
	int hp_from = h->active_player->hp;
	if (h->hp_display < hp_from) {
		h->hp_display++;
	} else if (h->hp_display > hp_from) {
		h->hp_display--;
	}
}

void hud_draw(Hud* h)
{
	inventory_draw (h);
	hp_draw (h);
	treasure_draw (h);
}

void hud_free(Hud* h)
{
	free(h);
}
